package print
import (
	"errors"
	"strings"
	"time"
	"dhfshop/models"
	"dhfshop/models/consts"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

/// 商户打印设置
type PrintSet struct {
	PrintSetId      int64  `orm:"column(print_set_id);pk;auto" json:"print_set_id" form:"print_set_id"`        //打印设置ID
	PartnerId       int64  `orm:"column(partner_id)" json:"partner_id" form:"partner_id"`                      //商户ID
    StoreId         int64  `orm:"column(store_id)" json:"store_id" form:"store_id"`                            //门店编号
	OrderPrintCnt   int    `orm:"column(order_print_cnt)" json:"order_print_cnt" form:"order_print_cnt"`       //待消费订单打印次数
	ConsumePrintCnt int    `orm:"column(consume_print_cnt)" json:"consume_print_cnt" form:"consume_print_cnt"` //消费完成打印次数
	ConfirmPrintCnt int    `orm:"column(confirm_print_cnt)" json:"confirm_print_cnt" form:"confirm_print_cnt"` //菜品下单确认打印次数
	CreatedAt    time.Time `orm:"column(created_at);auto_now_add;type(datetime)" json:"-"`
	CreatedAtStr string    `orm:"-" json:"created_at"`
	UpdatedAt    time.Time `orm:"column(updated_at);auto_now;type(datetime)" json:"-"`
	UpdatedAtStr string    `orm:"-" json:"updated_at"`
}

func init() {
	orm.RegisterModel(new(PrintSet))
}

func AddPrintSet(printSet *PrintSet) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(printSet)
	return
}

func GetPrintSetByStoreId(storeId int64) (printSet *PrintSet, err error) {
	o := models.GetDefaultDB()
	printSet = &PrintSet{StoreId: storeId}
	if err = o.Read(printSet, "StoreId"); err != nil {
		return
	}
	return
}

func GetAllPrintSets(query,orderBy map[string]string,fields []string,offset,limit int)([]*PrintSet, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(PrintSet))
	if start, ok := query["start_created"]; ok {
		if startTime, err := time.Parse(consts.DATELINKTIME_FORMAT, start); err == nil {
		    qs = qs.Filter("created_at__gte", startTime)
		}
		delete(query, "start_created")
	}
	if end, ok := query["end_created"]; ok {
		if endTime, err := time.Parse(consts.DATELINKTIME_FORMAT, end); err == nil {
	        qs = qs.Filter("created_at__lte", endTime)
	    }
		delete(query, "end_created")
	}
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, "|"); ok {
		    valueArr := strings.Split(v, "|")
			qs = qs.Filter(k, valueArr)
		}else{
		    qs = qs.Filter(k, v)
		}	
	}
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range orderBy {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*PrintSet
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		for _, uimod := range lists {
			uimod.CreatedAtStr = uimod.CreatedAt.Format(consts.DATETIME_FORMAT)
            uimod.UpdatedAtStr = uimod.UpdatedAt.Format(consts.DATETIME_FORMAT)
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdatePrintSetById(m *PrintSet, fields ...string) error {
	o := models.GetDefaultDB()
	v := PrintSet{PrintSetId: m.PrintSetId}
	if err := o.Read(&v); err != nil {
		return err
	}
	_, err := o.Update(m, fields...)
	return err
}

func DeletePrintSetById(printSetId int64) (err error) {
	o := models.GetDefaultDB()
	v := PrintSet{PrintSetId: printSetId}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}
